package com.chuji.crmcj.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.CarTypeStockActivity;
import com.chuji.crmcj.act.DealOrderAct;
import com.chuji.crmcj.act.DisposableAct;
import com.chuji.crmcj.act.FullPayCarAct;
import com.chuji.crmcj.act.MagLoseApproveActivity;
import com.chuji.crmcj.act.MagNoticeActivity;
import com.chuji.crmcj.act.MagWorkFormActivity;
import com.chuji.crmcj.act.SearchActivity;
import com.chuji.crmcj.adapter.ToolsAdapter;
import com.chuji.crmcj.bean.MagTodayInfo;
import com.chuji.crmcj.utils.CommonUtil;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.view.CustomerBar;
import com.jauker.widget.BadgeView;

/**
 * Created by w.pitt on 2016/1/28.
 */
public class MagHomeFragment extends BaseFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private CustomerBar mCbDefeatApproval;
    private CustomerBar mCbFullPayCar;
    private View view;
    private CustomerBar mCbDealOrder;
    private CustomerBar mCbDisposable;
    private GridView mGvTools;
    private ScrollView mScrollView;
    private String userID;
    private TextView mTv_week;
    private LinearLayout mLl_left;
    private TextView mTotalTask;
    private TextView mFirstTaskCount;
    private TextView mSecondTaskCount;
    private LinearLayout mLl_right;
    private TextView mOrderCount;
    private TextView mFailOrderCount;
    private TextView mTrialDriveCount;
    private RelativeLayout mRlSearchBar;
    private LinearLayout mLlMagager;
    private int roleType;
    private BadgeView badgeView;
    private View mllKongbai;
    private AutoTask task;

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = View.inflate(mContext, R.layout.page_mag_page, null);
        mScrollView = (ScrollView) view.findViewById(R.id.sv);

        mLlMagager = (LinearLayout) view.findViewById(R.id.ll_manager);
        mllKongbai = view.findViewById(R.id.ll_item_kongbai);
        mRlSearchBar = (RelativeLayout) view.findViewById(R.id.rl_searchBar);
        mGvTools = (GridView) view.findViewById(R.id.gv_tools);
        mCbDefeatApproval = (CustomerBar) view.findViewById(R.id.cb_defeat_approval);
        mCbFullPayCar = (CustomerBar) view.findViewById(R.id.cb_full_pay_car);
        mCbDealOrder = (CustomerBar) view.findViewById(R.id.cb_deal_order);
        mCbDisposable = (CustomerBar) view.findViewById(R.id.cb_disposable);
        mTv_week = (TextView) view.findViewById(R.id.tv_week);
        mLl_left = (LinearLayout) view.findViewById(R.id.ll_left);
        mTotalTask = (TextView) view.findViewById(R.id.totalTask);
        mFirstTaskCount = (TextView) view.findViewById(R.id.firstTaskCount);
        mSecondTaskCount = (TextView) view.findViewById(R.id.secondTaskCount);
        mLl_right = (LinearLayout) view.findViewById(R.id.ll_right);
        mOrderCount = (TextView) view.findViewById(R.id.orderCount);
        mFailOrderCount = (TextView) view.findViewById(R.id.failOrderCount);
        mTrialDriveCount = (TextView) view.findViewById(R.id.trialDriveCount);

        initData();
        return view;
    }

    @Override
    public void initData() {
        userID = SPUtils.getString(UIUtils.getContext(), "UserID", "");
        roleType = SPUtils.getInt(UIUtils.getContext(), "RoleType", -1);

        if (roleType == 2) {
            //经理端
            isGeneralMag = 0;
        } else if (roleType == 3) {
            //总经理端
            mLlMagager.setVisibility(View.GONE);
            isGeneralMag = 1;
            mllKongbai.setVisibility(View.GONE);
        }

        mTv_week.setText(CommonUtil.getStringDate("EEEE MM/dd"));
//        reqNetData();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        isFirst = true;

        task = new AutoTask();
//        if (free == 1) {
//            空闲状态
        task.start();
//        }
//        else {
//            task.stop();
//        }
    }

    private boolean isFirst = true;

    //    // handler类接收数据
//    Handler handler = new Handler() {
//        public void handleMessage(Message msg) {
//            if (msg.what == 1) {
//                System.out.println("receive....");
//                //经理端请求  数据
//                reqNetData();
//            }
//        }
//    };
//
    private class AutoTask implements Runnable {
        private boolean flag = false;

        @Override
        public void run() {
            if (flag) {
                UIUtils.postDelayed(this, 10000);
                //经理端请求  数据
                reqNetData();
            }
        }

        public void start() {
            if (!flag) {
                flag = true;
                UIUtils.removeCallbacks(this);
                if (isFirst) {
                    UIUtils.postDelayed(this, 0);
                    isFirst = false;
                } else {
                    UIUtils.postDelayed(this, 10000);
                }
            }
        }

        public void stop() {
            if (flag) {
                UIUtils.removeCallbacks(this);
                flag = false;
            }
        }
    }

//    // 线程类
//    class ThreadShow implements Runnable {
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    if (isFirst) {
//                        Thread.sleep(0);
//                        isFirst = false;
//                    } else {
//                        Thread.sleep(5000);
//                    }
//                    Message msg = new Message();
//                    msg.what = 1;
//                    handler.sendMessage(msg);
//                    System.out.println("send...");
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    System.out.println("thread error...");
//                }
//            }
//        }
//    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /*
    根据UserId进行判断
    0 普通经理
    1 总经理   不显示  mLlMagager.setVisible(View.Gone);
    */
    private int isGeneralMag = 0;

    private void reqNetData() {
        String strURL = String.format(UrlUtils.MANAGERINDEXPETER + "&UserID=%s&isGeneralManager=%d", userID, isGeneralMag);
        volleyRequest(strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                final MagTodayInfo magTodayInfo = JSON.parseObject(s, MagTodayInfo.class);
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if (magTodayInfo.getApiParamObj().size() != 0) {
                            ToolsAdapter adapter = new ToolsAdapter(3, magTodayInfo.getApiParamObj().get(0).getMessageCount());
                            mGvTools.setAdapter(adapter);
                            mTotalTask.setText("总客流：" + magTodayInfo.getApiParamObj().get(0).getTotalTask());
                            mOrderCount.setText("成交量：" + magTodayInfo.getApiParamObj().get(0).getOrderCount());
                            mFirstTaskCount.setText("首客流：" + magTodayInfo.getApiParamObj().get(0).getFirstTaskCount());
                            if (roleType == 2) {
                                mSecondTaskCount.setText("二次客流：" + magTodayInfo.getApiParamObj().get(0).getSecondTaskCount());
                            } else if (roleType == 3) {
                                mSecondTaskCount.setText("无效客流：" + magTodayInfo.getApiParamObj().get(0).getInvalidTaskCount());
                            }
                            mTrialDriveCount.setText("试乘试驾：" + magTodayInfo.getApiParamObj().get(0).getTrialDriveCount());
                            mFailOrderCount.setText("战败量：" + magTodayInfo.getApiParamObj().get(0).getFailOrderCount());

                            if (roleType == 2) {
                                //经理端  总经理端不显示
                                CommonUtil.setRedIcon(mCbDefeatApproval.getIcon(), magTodayInfo.getApiParamObj().get(0).getFailApproveCount());
                                CommonUtil.setRedIcon(mCbFullPayCar.getIcon(), magTodayInfo.getApiParamObj().get(0).getNowOrderCount());
                                CommonUtil.setRedIcon(mCbDealOrder.getIcon(), magTodayInfo.getApiParamObj().get(0).getOrderDealCount());

                                if (magTodayInfo.getApiParamObj().get(0).getComplainCount() > 0) {
                                    BadgeView badgeView = new BadgeView(UIUtils.getContext());
                                    badgeView.setTargetView(view);
                                    badgeView.setBackgroundResource(R.drawable.yuandian);
                                    badgeView.setBadgeGravity(Gravity.RIGHT | Gravity.TOP);
                                    mCbDisposable.getIcon().setVisibility(View.VISIBLE);
                                } else {
                                    mCbDisposable.getIcon().setVisibility(View.GONE);
                                }
//                                CommonUtil.setRedIcon(mCbDisposable.getIcon(), magTodayInfo.getApiParamObj().get(0).getComplainCount());
                                mCbDefeatApproval.setTime(magTodayInfo.getApiParamObj().get(0).getFailApproveTime());
                                mCbFullPayCar.setTime(magTodayInfo.getApiParamObj().get(0).getNowOrderTime());
                                mCbDealOrder.setTime(magTodayInfo.getApiParamObj().get(0).getOrderDealTime());
                                mCbDisposable.setTime(magTodayInfo.getApiParamObj().get(0).getComplainTime());
                            }
                        }
                    }
                });
            }
        });
    }


    @Override
    public void initListener() {
        super.initListener();
        mCbDefeatApproval.setOnClickListener(this);
        mCbFullPayCar.setOnClickListener(this);
        mCbDealOrder.setOnClickListener(this);
        mCbDisposable.setOnClickListener(this);
        mGvTools.setOnItemClickListener(this);
        mRlSearchBar.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cb_defeat_approval:
                UIUtils.startActivity(new Intent(mContext, MagLoseApproveActivity.class));
                break;
            case R.id.cb_full_pay_car:
                UIUtils.startActivity(new Intent(mContext, FullPayCarAct.class));
                break;
            case R.id.cb_deal_order:
                UIUtils.startActivity(new Intent(mContext, DealOrderAct.class));
                break;
            case R.id.cb_disposable:
                UIUtils.startActivity(new Intent(mContext, DisposableAct.class));
                break;
            case R.id.rl_searchBar:
                UIUtils.startActivity(new Intent(mContext, SearchActivity.class));
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        switch (position) {
            case 0:
                UIUtils.startActivity(new Intent(mContext, MagWorkFormActivity.class));
                break;
            case 1:
                UIUtils.startActivity(new Intent(mContext, MagNoticeActivity.class));
                break;
            case 2:
                UIUtils.startActivity(new Intent(mContext, CarTypeStockActivity.class));
                break;
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        task.stop();
        task = null;
    }
}

